package com.duke.shaking.widget;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.GridView;

import com.duke.shaking.Constants;
import com.duke.shaking.pojo.UserImage;
import com.duke.shaking.utils.DeviceUtils;

public class PhotoMgrGridView extends GridView {
	private static final String TAG = "PhotoMgrGridView";
	private PhotoMgrGridAdapter adapter;
	private ArrayList<UserImage> photos;
	
	private static final int VERTICAL_SPACING_DP = 5;
	private static final int HORIZONTAL_PADDING_DP = 10;
	private static final int PHOTO_COLUMNS = 4;
	private static final int HORIZONTAL_SPACING_PX = 10;
	
	public PhotoMgrGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		if (!this.isInEditMode()) {
			photos = loadPhotos();
			adapter = new PhotoMgrGridAdapter(context, photos);
			setAdapter(adapter);
		}
	}
	
	public void setEditable(boolean editable) {
		adapter.setEditable(editable);
	}

	private ArrayList<UserImage> loadPhotos() {
		ArrayList<UserImage> imagesUrl = new ArrayList<UserImage>();
		return imagesUrl;
	}
	
	public boolean isEditButton(int position) {
		if (photos == null || 
			(position >= photos.size()
			&& photos.size() < Constants.maxPhotosCount)) {
			return true;
		}
		return false;
	}
	
	public void addPhoto(UserImage img) {
		photos.add(img);
	}
	
	public void removePhoto(int position) {
		photos.remove(position);
	}
	
	public UserImage getPhoto(int position) {
		return photos.get(position);
	}
	
	public void setPhotos(ArrayList<UserImage> imgList) {
		this.photos = imgList;
	}
	
	public void addPhotos(List<UserImage> imgList) {
		this.photos.addAll(imgList);
	}
	
	public int getTotalCount() {
		return this.photos.size();
	}
	
	public ArrayList<UserImage> getPhotos() {
		return photos;
	}

	public void printPhotos() {
		Log.i(TAG, "---- print photos ----, there are " + photos.size() + " photos");
		for(UserImage img : photos) {
			Log.i(TAG, "[Photo] url:" + img.getUrl() + ";  pid:" + img.getPid());
		}
	}
	
	/**
	 * Reset the height of the grid view according to photo count
	 */
	public void updateHeight() {
		int width = DeviceUtils.getDisplayWidthPix();
		int colWidth = (width - DeviceUtils.dip2px(HORIZONTAL_PADDING_DP * 2) - 
				HORIZONTAL_SPACING_PX * (PHOTO_COLUMNS - 1)) / PHOTO_COLUMNS;
		
		Log.i(TAG, "the column height = " + colWidth + "px");
		
		int rows = this.getTotalCount() > 3 ? 2 : 1;
		Log.i(TAG, "there is " + rows + " rows photo");
		
		android.widget.LinearLayout.LayoutParams params = 
				new android.widget.LinearLayout.LayoutParams(
				android.widget.AbsListView.LayoutParams.MATCH_PARENT, 
				DeviceUtils.dip2px((rows + 1) * VERTICAL_SPACING_DP) + colWidth * rows);
		this.setLayoutParams(params);
	}
}
